/* beautify ignore:start */
import {provide, Directive, forwardRef, Input} from '@angular/core';
import {Control, NG_VALIDATORS, Validator} from '@angular/common';
/* beautify ignore:end */

@Directive({
    selector: '[equalTo]',
    providers: [provide(NG_VALIDATORS, {useExisting: EqualToValidator, multi: true})],
    inputs: ['target: equalTo']
})

export class EqualToValidator implements Validator {
    target: string;
    validate(c: Control): {[key: string]: any} {
        let t: any = c.root.find(this.target);
        let val: any;
        for (name in t.controls) {
            if (val === undefined) {
                val = t.controls[name].value
            } else {
                if (val === t.controls[name].value) {
                    return;
                }
            }
        }

        return {'equalTo': true};
    }
}
